import { DirectiveBinding } from "vue"

const Distance = 100
const Duration = 500

const map = new WeakMap<Element, Animation>()
const ob = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      const animation = map.get(entry.target)
      animation && animation.play()
      ob.unobserve(entry.target)
    }
  }
})

function isBelowViewport(el: Element) {
  const rect = el.getBoundingClientRect()
  return rect.top - window.innerHeight > 0
}

export default {
  mounted(el: HTMLElement, bindings: DirectiveBinding) {
    console.log(bindings.value, 'bindings')
    if (!isBelowViewport(el)) {
      return
    }
    const animate = el.animate([
      {
        transform: `translateY(${Distance}px)`,
        opacity: 0.5
      },
      { transform: 'translateY(0)', opacity: 1 }
    ], {
      duration: Duration,
      easing: 'ease-out',
      fill: 'forwards'
    })

    animate.pause()
    map.set(el, animate)
    ob.observe(el)
  },
  unmounted(el: HTMLElement) {
    ob.unobserve(el)
  }
}